/*
 * ============================================================================
 *
 *       Filename:  common.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2015年03月03日 14时15分15秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  jianxi sun (jianxi), ycsunjane@gmail.com
 *   Organization:  
 *
 * ============================================================================
 */
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/socket.h>
/* inet_ntoa */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "common.h"

void *safe_malloc(size_t size)
{
	char *ptr;
	if(!(ptr = malloc(size))) {
		sys_err("malloc failed\n");
		exit(-1);
	}
	memset(ptr, 0, size);
	return ptr;
}

int safe_socket(int domain, int type, int protocol)
{
	int fd;
	fd = socket(domain, type, 0);
	if(fd < 0) {
		sys_err("socket failed\n");
		exit(-1);
	}
	return fd;
}

int file_exist(char *filename)
{
	/*  try to open file to read */
	FILE *file;
	if ((file = fopen(filename, "r"))){
		fclose(file);
		return 1;
	}
	return 0;
}

char *mac_to_macstr(unsigned char *mac, char *macstr)
{
	sprintf(macstr, "%02x:%02x:%02x:%02x:%02x:%02x",
		mac[0], mac[1], mac[2], 
		mac[3], mac[4], mac[5]);
	return macstr;
}

char *ip_to_ipstr(struct sockaddr_in *addr, char *ipstr)
{
	strcpy(ipstr, inet_ntoa(addr->sin_addr));
	return ipstr;
}

int addr_equ(struct sockaddr_in *src, struct sockaddr_in *dest)
{
	return src->sin_addr.s_addr == dest->sin_addr.s_addr;
}
